package com.achobeta.recruitment.utils;

import com.achobeta.recruitment.config.AppConfig;
import com.achobeta.recruitment.config.QRCodeConstant;
import com.alibaba.fastjson.JSONObject;
import com.freewayso.image.combiner.ImageCombiner;
import com.freewayso.image.combiner.enums.OutputFormat;
import com.freewayso.image.combiner.enums.ZoomMode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-10-27
 * Time: 0:00
 */
@Slf4j
public class MediaUtils {

    // 获取UUID
    public static String getUUID_32() {
        return UUID.randomUUID().toString().replace("-", "");
    }
    /**
     * 上传本地资源
     * @param mergeImgPath
     * @param appId
     * @param secret
     * @return
     */
    public static String sendMedia(String mergeImgPath, String appId, String secret) {

        // 构造url
        String url = "https://api.weixin.qq.com/cgi-bin/media/upload" + HttpUtils.getQueryString(new HashMap<String, Object>() {{
            this.put("access_token", TokenUtils.getToken(appId, secret));
            this.put("type", "image");
        }});
        // 发起请求
        String response = HttpUtils.doPostByFile(url, null, mergeImgPath, "");
        System.out.println(response);
        return JSONObject.parseObject(response).getString("media_id");
    }

    /**
     * 拉取资源
     * @param mediaId
     * @param appId
     * @param secret
     * @return
     */
    public static String getMedia(String mediaId, String appId, String secret) {
        // 构造url
        String url = "https://api.weixin.qq.com/cgi-bin/media/get" + HttpUtils.getQueryString(new HashMap<String, Object>() {{
            this.put("access_token", TokenUtils.getToken(appId, secret));
            this.put("media_id", mediaId);
        }});
        System.out.println(url);
//        return HttpUtils.doGet(url, null);
        return HttpUtils.download(url, getUUID_32());
    }


    /**
     * 完整功能
     *
     * @param qrCodeUrl 二维码路径
     * @param headImgUrl 头像路径
     * @param wxId 微信号
     * @throws Exception
     * @return 图片保存路径
     */
    public static String mergeImage(String qrCodeUrl, String headImgUrl, String wxId) {
        try {
            String bgImagePath = QRCodeConstant.DOWNLOAD_PATH_PREFIX + QRCodeConstant.BACKGROUND_IMAGE_NAME;  //背景图（测试url形式）
            BufferedImage avatar = ImageIO.read(new URL(headImgUrl));           //头像
            BufferedImage bgImage = ImageIO.read(new FileInputStream(bgImagePath));

            //合成器和背景图（整个图片的宽高和相关计算依赖于背景图，所以背景图的大小是个基准）
            ImageCombiner combiner = new ImageCombiner(bgImage, OutputFormat.PNG);
            combiner.setBackgroundBlur(0);     //设置背景高斯模糊（毛玻璃效果）
            combiner.setCanvasRoundCorner(0); //设置整图圆角（输出格式必须为PNG）

            //头像（圆角设置一定的大小，可以把头像变成圆的）
            combiner.addImageElement(avatar, 450, 800, 725, 725, ZoomMode.WidthHeight)
                    .setRoundCorner(725)
                    .setBlur(0);       //高斯模糊，毛玻璃效果

            //二维码（强制按指定宽度、高度缩放）
            combiner.addImageElement(ImageIO.read(new FileInputStream(qrCodeUrl)), 680, 1872, 245, 245, ZoomMode.WidthHeight).setRoundCorner(10);

            //执行图片合并
            combiner.combine();

            //保存文件
            String path = QRCodeConstant.DOWNLOAD_PATH_PREFIX + wxId + "_full.png";
            combiner.save(path);
            new File(qrCodeUrl).delete();
            return path;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 一张背景拼接一张图
     * @param qrCodeUrl
     * @param bgImagePath
     * @param x
     * @param y
     * @param width
     * @param height
     * @return 拼接图的本地地址
     */

    public static String mergeImage(String qrCodeUrl, String bgImagePath, int x, int y, int width, int height) {
        try {
            BufferedImage bgImage = ImageIO.read(new FileInputStream(bgImagePath));

            //合成器和背景图（整个图片的宽高和相关计算依赖于背景图，所以背景图的大小是个基准）
            ImageCombiner combiner = new ImageCombiner(bgImage, OutputFormat.PNG);
            combiner.setBackgroundBlur(0);     //设置背景高斯模糊（毛玻璃效果）
            combiner.setCanvasRoundCorner(0); //设置整图圆角（输出格式必须为PNG）

            //二维码（强制按指定宽度、高度缩放）
            combiner.addImageElement(ImageIO.read(new FileInputStream(qrCodeUrl)), x, y, width, height, ZoomMode.WidthHeight).setRoundCorner(10);

            //执行图片合并
            combiner.combine();

            //保存文件
            String path = QRCodeConstant.DOWNLOAD_PATH_PREFIX
                    + getUUID_32() + "_full.png";
            combiner.save(path);
            return path;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *
     */
    public static String getImageUniquePath(String originName) {
        String path = AppConfig.MAP_ROOT;
        // 获取唯一id
        String id = getUUID_32();
        //获取文件后缀
        String suffix = originName.substring(originName.lastIndexOf("."));

        //拼接
        path += id + suffix;
        return path;
    }

    public static long loadFile(MultipartFile file, String path) {
        try {
            File loadFile = new File(path);
            file.transferTo(loadFile);
            return loadFile.length();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
